/*
package com.ruiyi.subway.service;

import com.ruiyi.subway.enums.ExceptionCode;
import com.ruiyi.subway.enums.TokenEnum;
import com.ruiyi.subway.exception.BusinessException;
import com.ruiyi.subway.exception.RestException;
import com.ruiyi.subway.model.RuiYiToken;
import com.ruiyi.subway.model.User;
import com.ruiyi.subway.utils.PropertiesUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Properties;

import static com.ruiyi.subway.utils.EncryptUtil.encrypt;


@Service
public class UserAuthService {
    @Autowired
    private UserService userService;
    private String desKey;
    private static Log log = LogFactory.getLog(UserAuthService.class);
    private Long token_timeout;         //token 超时
    private final int LOGIN_ERROR_NUM = 5;//登录失败锁定次数

    @PostConstruct
    public void loadKey() {
        InputStream ins = this.getClass().getClassLoader().getResourceAsStream("authKey");
        Properties properties = PropertiesUtil.loadClasspathProperties("vcs-client.properties");
        String tokenTimeout = properties.getProperty("token.timeout");
        token_timeout = Long.parseLong(tokenTimeout.trim());
        try {
            desKey = IOUtils.toString(ins, "utf-8");
        } catch (IOException e) {
            throw new RuntimeException("加载authKey文件失败", e);
        }
    }

    public TokenEnum authToken(String token) {
        try {
            RuiYiToken RuiYiToken = decryptToken(token);
            if(RuiYiToken == null || StringUtils.isEmpty(RuiYiToken.getLastLoginDate())){
                log.error("user == null, token = "+ token);
                return TokenEnum.ERROR;
            }
            // long 时间转 date
            Date lastLoginDate = convert2Date(RuiYiToken.getLastLoginDate());
            long time = new Date().getTime() - lastLoginDate.getTime();
            // 小于 超时时间
            if (time < token_timeout){
                return TokenEnum.SUCCESS;
            }else {
                return TokenEnum.TIMEOUT;
            }
        } catch (Exception e) {
            log.error("认证失败", e);
            return TokenEnum.ERROR;
        }
    }

    */
/**
     * token 续期
     * @param token
     * @return
     * @throws Exception
     *//*

    public String replaceToken(String token) throws Exception {
        TokenEnum tokenEnum = this.authToken(token);
        switch (tokenEnum) {
            case ERROR:
                throw new RestException("登录信息错误, 请重新登录");
            case TIMEOUT:
                throw new RestException("登录超时, 请重新登录");
            case SUCCESS:       //成功就更换token
                RuiYiToken RuiYiToken = this.getToken(token);
                RuiYiToken.setLastLoginDate(convert2String(new Date()));
                return this.createToken(RuiYiToken);
            default:
                return null;
        }
    }

    */
/**
     * 通过 token 获取 用户信息
     * @param token
     * @return
     *//*

    public User getUserByToken(String token) throws Exception {
        RuiYiToken RuiYiToken = getToken(token);
        return userService.selectByName(RuiYiToken.getName());
    }

    private RuiYiToken getToken(String token) throws Exception {
        return decryptToken(token);
    }

    public User authPassword(String userName, String password, String date) throws VcsBusinessException {

        User user  = userService.selectByName(userName);
        if (user.getName() == null ) {
            throw new BusinessException("用户名不存在, 请检查用户是否正确");
        }
        if(!user.isValid()) {
            throw BusinessException.buildException(ExceptionCode.USER_INVALID);
        }

        // 新用户 第一次登录 不存在 最后登录时间 需要创建
        if (StringUtils.isEmpty(user.getLastLoginDate())){
            user.setLastLoginDate(convert2String(new Date()));
        }

        Date lastLoginDate = convert2Date(user.getLastLoginDate());
        // 现在的时间 - 最后登录时间
        long time = new Date().getTime() - lastLoginDate.getTime();
        // 锁定次数
        int counter = user.getCounter();
        // 锁定时长 5分钟
        long failureTime = 5 * 60 * 1000;
        // 判断失败次数
        if (counter >= LOGIN_ERROR_NUM && time < failureTime) {
            throw new BusinessException("用户登录失败次数过多已被锁定，" + (failureTime - time) / 1000 + "秒后解锁");
        }

        user.setLastLoginDate(convert2String(new Date()));
        String userPassword ;
        try {
            userPassword = EncryptUtil.encryptMD5(date + user.getUserPass());
        } catch (EncryptException e) {
            e.printStackTrace();
            throw new BusinessException("用户密码错误!");
        }
        if (!userPassword.equals(password)) {
            // 到达锁定时间以后 重置登录次数
            if (counter == 5){
                counter = 0;
            }
            user.setCounter(counter + 1);
            userService.update(user);
            // 登录次数
            int num = LOGIN_ERROR_NUM - user.getCounter();
            String msg = "用户登录失败，重试次数还有" + num +"次";
            if (num == 0){
                msg = "用户登录失败次数过多已经锁定。5分钟后解除锁定";
            }
            throw new BusinessException(msg);
        }
        user.setCounter(0);
        userService.update(user);

        return user;
    }

    public String createToken(RuiYiToken token) throws VcsBusinessException {
        try {
            return encryptToken(token);
        } catch (Exception e) {
            throw new BusinessException("加密token失败", e);
        }

    }

    private String encryptToken(RuiYiToken token) throws Exception {
        byte[] dataBytes = new Gson().toJson(token).getBytes("utf-8");
        byte[] keyBytes = desKey.getBytes("utf-8");
        byte[] bt = encrypt(dataBytes, keyBytes);
        String strs = Base64.encodeBase64String(bt);
        return URLEncoder.encode(strs, "utf-8");
    }


    private RuiYiToken decryptToken(String token) throws Exception {
        if (token == null)
            return null;
        String decoded = URLDecoder.decode(token, "utf-8");
        byte[] buf = Base64.decodeBase64(decoded);
        byte[] keyBytes = desKey.getBytes("utf-8");
        byte[] bt = decrypt(buf, keyBytes);
        String dataJson = new String(bt, "utf-8");
        return new Gson().fromJson(dataJson, RuiYiToken.class);
    }
}
*/
